package pers.liyan.shi.springboot.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

import static pers.liyan.shi.springboot.utils.WebSocketUtils.ONLINE_USER_SESSIONS;
import static pers.liyan.shi.springboot.utils.WebSocketUtils.sendMessageAll;

/**
 * 聊天室WebSocket
 *
 * @author shily
 * @date 2019/6/18 10:15
 */
@Component
@ServerEndpoint("/chat-room/{username}")
public class ChatRoomServerEndpoint {

    private static Logger logger = LoggerFactory.getLogger(ChatRoomServerEndpoint.class);

    /**
     * 建立连接时调用
     *
     * @param username 用户名
     * @param session  用户session
     * @author shily
     * @date 2019/6/18 10:15
     */
    @OnOpen
    public void openSession(@PathParam("username") String username, Session session) {
        ONLINE_USER_SESSIONS.put(username, session);
        String message = String.format("欢迎用户[%s]来到聊天室!", username);
        logger.info("用户{}登录", username);
        sendMessageAll(message);
    }

    /**
     * 接收到用户发送的消息时调用
     *
     * @param username 用户名
     * @param message  消息内容
     * @author shily
     * @date 2019/6/18 10:17
     */
    @OnMessage
    public void OnMessage(@PathParam("username") String username, String message) {
        logger.info("用户{}发送消息[{}]", username, message);
        sendMessageAll(String.format("用户[%s]: %s", username, message));
    }

    /**
     * 连接关闭时调用
     * 从{@link pers.liyan.shi.springboot.utils.WebSocketUtils#ONLINE_USER_SESSIONS} 中移除当前用户并关闭session
     *
     * @param username 用户名
     * @param session  用户session
     * @author shily
     * @date 2019/6/18 10:24
     */
    @OnClose
    public void closeSession(@PathParam("username") String username, Session session) {
        ONLINE_USER_SESSIONS.remove(username);
        sendMessageAll(String.format("用户[%s]离开了聊天室", username));
        try {
            session.close();
        } catch (IOException e) {
            logger.error("关闭用户{}的session出错", username, e);
        }
    }

    /**
     * 发生异常时调用
     *
     * @param session session
     * @param throwable 异常
     * @author shily
     * @date 2019/6/18 10:29
     */
    @OnError
    public void onError(Session session, Throwable throwable) {

        try {
            session.close();
        } catch (IOException e) {
            logger.error("关闭session出错", e);
        }

        logger.info("Throwable msg", throwable.getMessage());

    }

}
